// src-tauri/src/trust_tree_signed.rs
use super::crypto::{CryptoService, CryptoError};
use serde::{Deserialize, Serialize};

impl TrustTree {
    /// 为证书生成数字签名
    pub fn sign_certificate(
        &self,
        crypto_service: &CryptoService,
        certificate_data: &TrustCertificate,
        signer_private_key: &[u8],
    ) -> Result<String, CryptoError> {
        // 准备要签名的数据（排除签名字段本身）
        let signable_data = self.prepare_signable_data(certificate_data);
        
        // 使用加密服务进行签名
        crypto_service.sign_data(&certificate_data.issued_by, &signable_data)
    }

    /// 准备用于签名的证书数据
    fn prepare_signable_data(&self, certificate: &TrustCertificate) -> Vec<u8> {
        // 创建不包含签名字段的证书副本
        let signable_cert = SignableCertificate {
            peer_id: certificate.peer_id.clone(),
            public_key: certificate.public_key.clone(),
            role: certificate.role.clone(),
            trust_level: certificate.trust_level,
            parent_peer_id: certificate.parent_peer_id.clone(),
            issued_by: certificate.issued_by.clone(),
            issue_date: certificate.issue_date,
            expiry_date: certificate.expiry_date,
            max_subordinates: certificate.max_subordinates,
            current_subordinates: certificate.current_subordinates,
            is_active: certificate.is_active,
        };

        // 序列化为JSON进行签名（确保确定性）
        serde_json::to_vec(&signable_cert)
            .expect("Failed to serialize certificate for signing")
    }

    /// 验证证书签名
    pub fn verify_certificate_signature(
        &self,
        crypto_service: &CryptoService,
        certificate: &TrustCertificate,
        issuer_public_key: &str,
    ) -> Result<bool, CryptoError> {
        let signable_data = self.prepare_signable_data(certificate);
        crypto_service.verify_signature(issuer_public_key, &signable_data, &certificate.signature)
    }

    /// 授权下级节点（带完整签名）
    pub fn authorize_subordinate_signed(
        &mut self,
        crypto_service: &CryptoService,
        issuer_peer_id: String,
        applicant_peer_id: String,
        applicant_public_key: String,
    ) -> Result<TrustCertificate, CryptoError> {
        // 验证签发者权限（与之前相同）
        let issuer_cert = self.certificates.get(&issuer_peer_id)
            .ok_or(CryptoError("Issuer not found".to_string()))?;

        if !issuer_cert.is_active {
            return Err(CryptoError("Issuer certificate is not active".to_string()));
        }

        if issuer_cert.trust_level >= self.max_depth {
            return Err(CryptoError("Cannot authorize subordinates at maximum depth".to_string()));
        }

        if issuer_cert.current_subordinates >= issuer_cert.max_subordinates {
            return Err(CryptoError("Issuer has reached maximum subordinate limit".to_string()));
        }

        // 创建新证书（无签名）
        let mut new_certificate = TrustCertificate {
            peer_id: applicant_peer_id.clone(),
            public_key: applicant_public_key,
            role: PeerRole::Trusted,
            trust_level: issuer_cert.trust_level + 1,
            parent_peer_id: issuer_peer_id.clone(),
            issued_by: issuer_peer_id.clone(),
            issue_date: current_timestamp(),
            expiry_date: current_timestamp() + 180 * 24 * 60 * 60,
            signature: "".to_string(), // 临时空签名
            max_subordinates: self.max_children_per_node,
            current_subordinates: 0,
            is_active: true,
        };

        // 生成数字签名
        let signature = self.sign_certificate(crypto_service, &new_certificate, &[])?;
        new_certificate.signature = signature;

        // 验证签名（确保正确性）
        let issuer_public_key = &issuer_cert.public_key;
        if !self.verify_certificate_signature(crypto_service, &new_certificate, issuer_public_key)? {
            return Err(CryptoError("Certificate signature verification failed after signing".to_string()));
        }

        // 更新数据结构（与之前相同）
        self.certificates.insert(applicant_peer_id.clone(), new_certificate.clone());
        
        self.children_map.entry(issuer_peer_id.clone())
            .or_insert_with(Vec::new)
            .push(applicant_peer_id.clone());
        self.children_map.insert(applicant_peer_id.clone(), Vec::new());

        if let Some(issuer_cert) = self.certificates.get_mut(&issuer_peer_id) {
            issuer_cert.current_subordinates += 1;
        }

        Ok(new_certificate)
    }

    /// 验证整个信任链的签名
    pub fn validate_trust_chain_signatures(
        &self,
        crypto_service: &CryptoService,
        target_peer_id: &str,
    ) -> Result<Vec<SignatureValidation>, CryptoError> {
        let mut current_id = target_peer_id;
        let mut validations = Vec::new();
        let mut visited = std::collections::HashSet::new();

        while let Some(certificate) = self.certificates.get(current_id) {
            // 检测循环
            if visited.contains(current_id) {
                return Err(CryptoError("Certificate chain contains a loop".to_string()));
            }
            visited.insert(current_id);

            // 获取签发者公钥
            let issuer_cert = self.certificates.get(&certificate.issued_by)
                .ok_or_else(|| CryptoError(format!("Issuer certificate not found: {}", certificate.issued_by)))?;

            // 验证签名
            let is_valid = self.verify_certificate_signature(
                crypto_service, 
                certificate, 
                &issuer_cert.public_key
            )?;

            validations.push(SignatureValidation {
                peer_id: certificate.peer_id.clone(),
                issuer_id: certificate.issued_by.clone(),
                is_valid,
                trust_level: certificate.trust_level,
            });

            // 到达God Peer，停止验证
            if self.is_god_peer(current_id) {
                break;
            }

            current_id = &certificate.parent_peer_id;
        }

        // 检查所有签名是否有效
        let all_valid = validations.iter().all(|v| v.is_valid);
        if !all_valid {
            return Err(CryptoError("Trust chain contains invalid signatures".to_string()));
        }

        Ok(validations)
    }
}

/// 用于签名的证书数据结构（不包含签名字段）
#[derive(Serialize, Deserialize)]
struct SignableCertificate {
    pub peer_id: String,
    pub public_key: String,
    pub role: PeerRole,
    pub trust_level: u8,
    pub parent_peer_id: String,
    pub issued_by: String,
    pub issue_date: u64,
    pub expiry_date: u64,
    pub max_subordinates: u8,
    pub current_subordinates: u8,
    pub is_active: bool,
}

/// 签名验证结果
#[derive(Serialize, Deserialize, Clone)]
pub struct SignatureValidation {
    pub peer_id: String,
    pub issuer_id: String,
    pub is_valid: bool,
    pub trust_level: u8,
}